using System;
using System.Data;
using System.Windows.Forms;

using Tino.Core;

namespace Tino
{
    public class RefreshAutoCompletionSearchBox : ICommand
    {
        RefreshAutoCompletionSearchBoxDelegate invokeMe;
        TextBox inputSearch;

        delegate DataTable RefreshAutoCompletionSearchBoxDelegate();

        public RefreshAutoCompletionSearchBox(TextBox InputSearch)
        {
            inputSearch = InputSearch;

            TagElement tagElement = new TagElement();
            invokeMe = new RefreshAutoCompletionSearchBoxDelegate(tagElement.GetTags);
        }

        void Callback(IAsyncResult ar)
        {
            // get the dataset as output
            DataTable dt = invokeMe.EndInvoke(ar);

            // update the grid a thread safe fasion!
            MethodInvoker updateSearchSource = delegate
            {
                AutoCompleteStringCollection tags = new AutoCompleteStringCollection();
                foreach (DataRow dr in dt.Rows)
                {
                    tags.Add((string)dr["Name"]);
                }

                inputSearch.AutoCompleteMode = AutoCompleteMode.Append;
                inputSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
                inputSearch.AutoCompleteCustomSource = tags;
            };

            if (inputSearch.InvokeRequired)
            {
                inputSearch.Invoke(updateSearchSource);
            }
            else
            {
                updateSearchSource();
            }
        }

        #region ICommand Members

        public void Execute()
        {
            invokeMe.BeginInvoke(this.Callback, null);
        }

        #endregion
    }
}
